package util;





import org.testng.annotations.AfterTest;

import java.sql.*;

public class DBUtil {
     private static Connection connection;
     private static Statement statement;
     private static PreparedStatement ps;
     private static ResultSet resultSet;

     public static Connection getConnection(){
         try{
             Class.forName("com.mysql.cj.jdbc.Driver");
              connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC","root","root");
         }
         catch (Exception e){
             e.printStackTrace();
         }
         //无论是否出现异常都会执行的模块
          finally {
             return connection;
         }
     }
    public static void closeAll(Connection connection,Statement statement,ResultSet resultSet){

         try {
             if (resultSet != null)
                 resultSet.close();
             if (statement != null)
                 statement.close();
             if (connection != null)
                 connection.close();
         }
         catch (Exception e){
             e.printStackTrace();
         }
    }
    //通用的查询
    public static ResultSet executeQuery(String sql){
         connection=getConnection();
        try {
            statement=connection.createStatement();
            resultSet=statement.executeQuery(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

         return resultSet;
    }




//    @Test
//    public void test(){
//         try{
//             Class.forName("com.mysql.cj.jdbc.Driver");
//             Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC","root","");
//             String sql="delete from student where id=?";
//             PreparedStatement ps=connection.prepareStatement(sql);
//             ps.setInt(1,107);
//             ps.execute();
//         }
//         catch (Exception e){
//             e.printStackTrace();
//         }
//
//
//    }
public static PreparedStatement getPreparedStatement(String sql,Object[] params) throws SQLException {
    PreparedStatement ps = getConnection().prepareStatement(sql);
    if(params!=null){
        for(int i=0;i<params.length;i++){
            ps.setObject(i+1, params[i]);
        }
    }
    return ps;
}
    //通用的增删改
    public static  boolean executeUpdate(String sql,Object[] params){

        try{
            ps=getPreparedStatement(sql,params);
            int count=ps.executeUpdate();
            if(count>0){
                return true;
            }else{
                return false;
            }
        } catch(SQLException e){
            e.printStackTrace();
            return false;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }finally{
            closeAll(connection, ps, null);
        }
    }
}
